package org.lex.swing.widgets;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;

import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;

import org.lex.swing.Swings;
import org.lex.swing.table.TableHelper;
import org.lex.utils.Pair;


public class SystemInfoTable extends JTable {
	public static void main(String[] args) {
		// Swings.show( new JScrollPane( new SystemInfoTable() ) );
		Swings.show(new JScrollPane(new JTable(TableHelper.createModel(System.getenv(), new Comparator<String>() {
			@Override
			public int compare(String o1, String o2) {
				return o1.compareTo(o2);
			}
		}))));
	}

	public SystemInfoTable() {
		super(createTableModel());
		this.setAutoCreateRowSorter(true);
		this.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		this.getRowSorter().toggleSortOrder(0);
		TableColumn column = this.getColumnModel().getColumn(0);
		column.setPreferredWidth(180);
		column = this.getColumnModel().getColumn(1);
		column.setPreferredWidth(375);
	}

	private static TableModel createTableModel() {
		Properties p = System.getProperties();
		SystemInfoTableModel.setupLineSeparator(p);
		return TableHelper.createModel(p);
	}

	static class SystemInfoTableModel extends AbstractTableModel {
		private List<Pair<String, String>> data = null;

		public SystemInfoTableModel() {
			Properties p = System.getProperties();
			setupLineSeparator(p);
			Enumeration<?> keys = p.propertyNames();
			this.data = new ArrayList<Pair<String, String>>(p.size());
			while (keys.hasMoreElements()) {
				String key = keys.nextElement().toString();
				data.add(new Pair<String, String>(key, p.getProperty(key)));
			}
			Collections.sort(data, new Comparator<Pair<String, String>>() {
				public int compare(Pair<String, String> o1, Pair<String, String> o2) {
					return o1.first().compareTo(o2.first());
				}
			});
		}

		static void setupLineSeparator(Properties p) {
			String sep = p.getProperty("line.separator");
			StringBuilder buf = new StringBuilder(sep.length());
			for (int i = 0; i < sep.length(); i++) {
				char ch = sep.charAt(i);
				switch (ch) {
				case '\n':
					buf.append("\\n");
					break;
				case '\r':
					buf.append("\\r");
					break;
				}
			}
			p.setProperty("line.separator", buf.toString());
		}

		public String getColumnName(int column) {
			if (0 == column)
				return "Name";
			return "Value";
		}

		public int getColumnCount() {
			return 2;
		}

		public int getRowCount() {
			return data.size();
		}

		public Object getValueAt(int row, int column) {
			if (0 == column)
				return data.get(row).first();
			else
				return data.get(row).second();
		}
	}
}
